#include "relationbutton.h"

#include "uml/umlrelationalitem.h"

RelationButton::RelationButton(QGraphicsObject *parent) : QGraphicsItemGroup(parent)
{
    this->_ishovered = false;
    this->_isPressed = false;

    this->_pen.setWidth(.5);
    this->_brush.setColor(Qt::white);
    this->_brush.setStyle(Qt::SolidPattern);
    this->_hoverBrush.setColor(QColor("#dee8f4"));
    this->_hoverBrush.setStyle(Qt::SolidPattern);

    this->setAcceptHoverEvents(true);

    this->setFlag(QGraphicsItem::ItemSendsGeometryChanges);

    this->updateBoundingBox();
}

RelationButton::~RelationButton()
{
    qDebug() << "deleting RelationButton";
}

void RelationButton::setRelationalItem(UmlRelationalItem *relationalItem)
{
    this->_relationalItem = relationalItem;
    QObject::connect(this, SIGNAL(startRelationDrag(DraggedRelation*)), this->_relationalItem->project(), SLOT(startRelationDrag(DraggedRelation*)));
}

void RelationButton::updateBoundingBox()
{
    this->prepareGeometryChange();
    this->_boundingBox.setTopLeft(QPoint(0, 0));
    this->_boundingBox.setBottomRight(QPoint(20, 20));
}

QRectF RelationButton::boundingRect() const
{
    return this->_boundingBox;
}

void RelationButton::startRelationDrag()
{
    emit this->startRelationDrag(this->draggedRelation());
}

qreal RelationButton::width()
{
    return this->_boundingBox.width();
}

qreal RelationButton::height()
{
    return this->_boundingBox.height();
}

void RelationButton::setTopLeft(QPointF pos)
{
    this->setPos(pos);
}

void RelationButton::setIsHovered(bool isHovered)
{
    this->_ishovered = isHovered;
}

void RelationButton::paint(QPainter *painter, const QStyleOptionGraphicsItem *option, QWidget *widget)
{
    if (this->_ishovered) {
        painter->fillRect(this->_boundingBox, Qt::lightGray);
    } else {
        painter->fillRect(this->_boundingBox, Qt::white);
    }

    QPainterPath path;
    path.addRect(this->_boundingBox);

    QPen borderPen;
    borderPen.setWidth(1);
    borderPen.setColor(Qt::black);

    painter->strokePath(path, borderPen);

    QGraphicsItemGroup::paint(painter, option, widget);
}

QVariant RelationButton::itemChange(GraphicsItemChange change, const QVariant &value)
{
    if (change == QGraphicsItem::ItemSceneHasChanged) {

        this->_decorator.setParentItem(this);
        this->addToGroup(&this->_decorator);

        this->updateBoundingBox();
    }

    return QGraphicsItemGroup::itemChange(change, value);
}
